// User.js
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const validator = require('validator');

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: [true, '邮箱不能为空'],
    unique: true,
    validate: [validator.isEmail, '请输入有效的邮箱地址'],
    lowercase: true
  },
  nickname: {
    type: String,
    required: [true, '昵称不能为空'],
    maxlength: 50,
    trim: true
  },
  password: {
    type: String,
    required: [true, '密码不能为空'],
    minlength: 6,
    select: false
  },
  role: {
    type: String,
    enum: ['admin', 'teacher', 'student'],
  },
  department: {
    type: String,
  },
  studentId: {
    type: String,
    unique: true,
    sparse: true
  },
  isVerified: {
    type: Boolean,
    default: false
  },
  avatar: {
    type: String,
    default: '/default-avatar.png' // 默认头像路径
  },
  bio: {
    type: String,
    maxlength: 200,
    default: ''
  }
}, { timestamps: true });

// 密码加密中间件
userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) return next();
  this.password = await bcrypt.hash(this.password, 12);
  next();
});

// 密码比对方法
userSchema.methods.comparePassword = async function(candidatePassword) {
  return await bcrypt.compare(candidatePassword, this.password);
};

module.exports = mongoose.model('User', userSchema);